#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Software : PyCharm
# @Time    : 2025-01-20 10:37
# @Author  : gzh
# @File : TreeView.py

from . import Treeview, Scrollbar, Combobox, Style, tkf, Toplevel, StringVar, Label, Button

class TreeView(Treeview):
    def __init__(self, master, columns=('', ), columns_w=None, f=15):
        font = tkf.Font(size=f, family='楷体')
        style = Style()
        style.configure("Treeview", font=font, rowheight=25)
        style.configure("Treeview.Heading", foreground="black", background="red", fieldbackground="red",
                        bordercolor="blue", font=font)
        super().__init__(master=master,  # 父容器
            height=15,  # 表格显示的行数,height行
            columns=columns,  # 显示的列
            show='headings'  # 隐藏首列
                         )
        yscroll = Scrollbar(self, orient='vertical')
        self.configure(yscrollcommand=yscroll.set)
        yscroll.config(command=self.yview)
        yscroll.pack(side='right', fill='y')
        self.bind("<<TreeviewSelect>>", lambda event: self.treeview_select())
        if columns_w is None:
            columns_w = [1 for _ in columns]
        elif len(columns) > len(columns_w):
            columns_w = [int(i) for i in columns_w] + [1 for _ in range(len(columns) - len(columns_w))]
        else:
            columns_w  = [int(i) for i in columns_w]
        self.bind("<Configure>", lambda event: self.treeview_configure(master, columns, columns_w))
        self.tag_configure('oddrow', background="#e0e0e0")
        self.tag_configure('evenrow', background="#ffffff")
        self.tag_configure('newrow', background="#0000ff")
        self.item_key = None
        self._items_all = 0

    def treeview_select(self):  # 单击绑定程序
        try:
            self.item_key = self.selection()[0]
            item_text = self.item(self.item_key, 'values')
        except IndexError:
            self.item_key = None
            item_text = ()
        return item_text

    def treeview_configure(self, master, columns, columns_w):  # 表单设置
        w = self.winfo_width()
        widths = [int(w * (i / sum(columns_w))) for i in columns_w]
        for index, column in enumerate(columns):
            self.heading(column=column, text=column, anchor='center', command=lambda name=column, i=index:
                        TreeViewTitleSelect(master.parent, name, i, self, self.treeview_get))  # 定义表头
            self.column(column=column, width=widths[index], minwidth=0, anchor='center')  # 定义列

    def treeview_set_data(self, datas):  # 更新全部表单数据
        self.treeview_clear()
        for index, data in enumerate(datas):
            tag = 'oddrow' if index % 2 == 1 else 'evenrow'
            self.insert('', 'end', values=data, text=f'{index}', tags=tag)
        self._items_all = len(datas)

    def treeview_add_data(self, datas):  # 添加表单数据在后面添加
        if self._items_all % 2 == 1:
            t = 0
        else:
            t = 1
        for index, data in enumerate(datas):
            tag = 'oddrow' if index % 2 == t else 'evenrow'
            self.insert('', 'end', values=data, text=f'{index}', tags=tag)
        self._items_all += len(datas)

    def treeview_add_data_new(self, d): # 在表单前面添加新的数据
        self.insert('', 0, values=d, text=f'{self._items_all}', tags='newrow')
        self._items_all += 1
        self.item_key = self.get_children()[0]

    def treeview_clear(self):  # 清空表单条目
        item = self.get_children()
        for i in item:
            self.delete(i)
            
    def treeview_delete(self):  # 删除表单条目
        if self.item_key is not None:
            self.delete(self.item_key)
            self.item_key = None
            self._items_all -= 1
        else:
            pass

    def treeview_get(self, index, value):  # 根据表单表头进行筛选
        item = self.get_children()
        for i in item:
            d = self.item(i, 'values')
            if d[index] != value:
                self.delete(i)

class TreeViewTitleSelect(Toplevel):
    """
    点击表单表头弹出提示框可选中单个表头项目进行表单数据筛选
    """
    def __init__(self, parent, title, index, table, fanc):
        super().__init__(parent)
        self.wm_overrideredirect(True)
        self.wm_attributes("-topmost", True)
        self.free_w = int(500 * parent.winfo_ki)
        self.free_h = int(350 * parent.winfo_ki)
        self.x_position = int((parent.now_w - self.free_w) / 2)
        self.y_position = int((parent.now_h - self.free_h) / 2)
        self.geometry(f'{self.free_w}x{self.free_h}+{self.x_position}+{self.y_position}')
        self.config(bg='#f07f7f')
        self.parent = parent
        self.com_value = StringVar(master=self, value='')
        item = table.get_children()
        values = list(set([table.item(i, 'values')[index] for i in item]))
        Label(self, text=f"{title}筛选", font=parent.f18, justify='center', bd=0, relief='flat',
              bg='#f07f7f').place(relx=0, rely=0.2, relwidth=1, relheight=0.1)
        com = Combobox(self, textvariable=self.com_value, values=values)
        com.place(relx=0.2, rely=0.4, relwidth=0.6, relheight=0.1)
        if len(values) > 0:
            self.com_value.set(values[0])
        bt1 = Button(self, text='筛选', font=parent.f18, wraplength=480,
                     command=lambda: self.btn_ok(index), bd=2, fg='#000000', bg='green')
        bt1.place(relx=0.1, rely=0.85, relwidth=0.2, relheight=0.1)
        bt2 = Button(self, text='取消', font=parent.f18, wraplength=340,
                     command=self.btn_nok, bd=2, fg='#000000', bg='green')
        bt2.place(relx=0.7, rely=0.85, relwidth=0.2, relheight=0.1)
        bt1.bind('<Return>', lambda event,: self.btn_ok(index))
        bt2.bind('<Return>', lambda event,: self.btn_nok())

        self.fanc = fanc
        self.grab_set()

    def btn_ok(self, index):
        self.fanc(index, self.com_value.get())
        self.destroy()

    def btn_nok(self):
        self.destroy()



if __name__ == '__main__':
    from TkParent import _Tks
    _Tks.window_default('', (1180, 700, 0, 0))
    a = TreeView(_Tks, ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'], columns_w=(2, 3))
    a.pack(fill='both', expand=True)
    _Tks.start()